// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const _ = db.command
const $ = _.aggregate

// var event = {
//   month:1,
//   idolId:'17453ede608fd98306b4683603ce5f48'
// }
// 云函数入口函数
/**
 * 获取某偶像某期的粉丝投票榜(根据 idolId，week，month)
 * @param {*} event 
 * @param {*} context 
 */
exports.main = async (event, context) => {
  if (event.month) {
    // 月榜用户
    return await db.collection('ad_vote_logs').aggregate()
      .match({
        month: event.month,
        idol_id: event.idolId
      })
      .group({
        _id: {
          _openid: '$_openid',
          month: '$month',
          idol_id: '$idol_id'
        },
        total: $.sum(1),
        total_point: $.sum('$point')
      })
      .sort({
        total_point: -1
      })
      .limit(10)
      .replaceRoot({
        // newRoot: $.mergeObjects([ $.arrayElemAt(['$_id', 0]), '$$ROOT' ])
        newRoot: $.mergeObjects(['$_id', '$$ROOT'])
      })
      .lookup({
        from: "userinfo",
        localField: "_openid",
        foreignField: "_openid",
        as: "user"
      })
      .unwind({
        path: '$user',
        preserveNullAndEmptyArrays: true
      })
      // .replaceRoot({
      //   newRoot: $.mergeObjects(['$_id', '$$ROOT'][ $.arrayElemAt(['$userinfo', 0]), '$$ROOT' ])
      // })
      .project({
        _id: 0
        // ,
        // userinfo: 0,
        // nickName: 1
      })
      .end()

  } else {
    // 周榜用户
    return await db.collection('ad_vote_logs').aggregate()
      .match({
        week: event.week,
        idol_id: event.idolId
      })
      .group({
        _id: {
          _openid: '$_openid',
          week: '$week',
          idol_id: '$idol_id'
        },
        total: $.sum(1),
        total_point: $.sum('$point')
      })
      .sort({
        total_point: -1
      })
      .limit(10)
      .replaceRoot({
        // newRoot: $.mergeObjects([ $.arrayElemAt(['$_id', 0]), '$$ROOT' ])
        newRoot: $.mergeObjects(['$_id', '$$ROOT'])
      })
      .lookup({
        from: "userinfo",
        localField: "_openid",
        foreignField: "_openid",
        as: "user"
      })
      .unwind({
        path: '$user',
        preserveNullAndEmptyArrays: true
      })
      // .replaceRoot({
      //   newRoot: $.mergeObjects(['$_id', '$$ROOT'][ $.arrayElemAt(['$userinfo', 0]), '$$ROOT' ])
      // })
      .project({
        _id: 0
        // ,
        // userinfo: 0,
        // nickName: 1
      })
      .end()
  }
}